package com.kanq.controller;

import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.spec.McpSchema;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/mcp")
public class MCPController {

    @Resource
    private ChatClient client;

    @Resource
    private List<McpSyncClient> mcpClientList;

    @GetMapping("/ai/mcp/generate")
    public Map<String, String> generate(@RequestParam(value = "message", defaultValue = "几点了?") String message) {
        return Map.of("generation", client.prompt(message).call().content());
    }

    @GetMapping("/ai/mcp/servers")
    public List<McpSyncClient> servers() {
        return mcpClientList;
    }

    @GetMapping("/ai/mcp/tools")
    public McpSchema.ListToolsResult tools(String name) {
        return mcpClientList.stream().filter(mcpSyncClient ->
                StringUtils.endsWithIgnoreCase(name, mcpSyncClient.getServerInfo().name())
        ).findFirst().get().listTools();
    }

    @GetMapping("/ai/mcp/resources")
    public McpSchema.ListResourcesResult resources(String name) {
        return mcpClientList.stream().filter(mcpSyncClient ->
                StringUtils.endsWithIgnoreCase(name, mcpSyncClient.getServerInfo().name())
        ).findFirst().get().listResources();
    }

    @GetMapping("/ai/mcp/prompts")
    public McpSchema.ListPromptsResult prompts(String name) {
        return mcpClientList.stream().filter(mcpSyncClient ->
                StringUtils.endsWithIgnoreCase(name, mcpSyncClient.getServerInfo().name())
        ).findFirst().get().listPrompts();
    }

}
